import React, { useState, useEffect } from 'react';
import styles from './apply.less';
import './ui-reset.less';
import { Picker, List } from 'antd-mobile';
import NewsCard from '../../components/newsCard';
import { useEventTarget } from 'ahooks';
import { useDispatch, useSelector, useParams, useHistory } from 'dva';
import InViewPort from '../../components/InViewPort';
import moment from 'moment';

import IconWebsite from '../../assets/business-match/icon-website.png';
import IconError from '../../assets/business-match/icon-error.png';
import { Toast } from 'antd-mobile';

import Modal from './modal';

const tabs = [
  {
    id: 0,
    label: '5月6日',
  },
  {
    id: 1,
    label: '5月7日',
  },
  {
    id: 2,
    label: '5月8日',
  },
];

const ErrorMessage = (props) => {
  return (
    <div className={`${styles.flex} ${styles.errorMessageBox}`}>
      <img
        style={{
          marginRight: 2,
        }}
        src={IconError}
        className={styles.errorIcon}
      />
      <span className={styles.errorLabel}>{props.message}</span>
    </div>
  );
};

function Index() {
  const history = useHistory();
  const dispatch = useDispatch();
  const { id, date } = useParams();
  const applyDate = moment(date).format('M月D日');
  const { businessMatchDetail = {}, articleCategoryList = [] } = useSelector(({ index }) => index);
  const [checkedTimeIndex, setCheckedTimeIndex] = useState(0);
  const [companyName, { onChange: setCompanyName }] = useEventTarget({ initialValue: '' });
  const [boothNumber, { onChange: setBoothNumber }] = useEventTarget({ initialValue: '' });
  const [contact, { onChange: setContact }] = useEventTarget({ initialValue: '' });
  const [mobile, { onChange: setMobile }] = useEventTarget({ initialValue: '' });
  const [venueNumber, setVenueNumber] = useState();
  const [errorFields, setErrorFields] = useState([]);
  const [isFail, setIsFail] = useState(false);

  const venues = ['E1', 'E2', 'E3', 'E4', 'E5', 'E6', 'E7', 'W1', 'W2', 'W3', 'OE9', 'OE10'];

  const formatTime = (time, format) => {
    return moment(time).format(format);
  };

  const getDetail = () => {
    const payload = {
      id,
    };
    dispatch({
      type: 'index/apiGetBusinessMatchDetail',
      payload,
    });
  };

  const submit = () => {
    const errors = [];
    if (!companyName) {
      errors.push('companyName');
    }
    if (!venueNumber) {
      errors.push('venueNumber');
    }
    const reg = /^\d{1,4}$/;
    if (!reg.test(boothNumber)) {
      errors.push('boothNumber');
    }
    if (!contact) {
      errors.push('contact');
    }
    if (!mobile) {
      errors.push('mobile');
    }
    if (!validatePhone(mobile)) {
      errors.push('mobile');
    }
    if (errors.length) {
      setErrorFields(errors);
      return;
    }
    setErrorFields([]);
    const payload = {
      companyName,
      boothNumber,
      contact,
      venueNumber,
      contactInformation: mobile,
      businessOpportunityMeet: {
        id: businessMatchDetail.businessOpportunityMeets[checkedTimeIndex].id,
      },
    };
    dispatch({
      type: 'index/apiAddBusinessMatchApply',
      payload,
      callback: onSuccess,
      errCallback: onError,
    });
  };

  const onError = () => {
    getDetail();
  };

  const onSuccess = () => {
    history.push('/business-match/result');
  };

  const validatePhone = () => {
    const reg = /^1(3\d|4[5-9]|5[0-35-9]|6[2567]|7[0-8]|8\d|9[0-35-9])\d{8}$/;
    return reg.test(mobile);
  };

  const toggleTimeItem = (index) => {
    setCheckedTimeIndex(index);
  };

  useEffect(() => {
    if (businessMatchDetail && businessMatchDetail.businessOpportunityMeets) {
      const idx = businessMatchDetail.businessOpportunityMeets.findIndex((item) => !item.reserved);
      setCheckedTimeIndex(idx);
    }
  }, [businessMatchDetail]);

  useEffect(() => {
    getDetail();
    // dispatch({ type: 'index/getVenues', payload: {}, isReset: true });
  }, []);

  useEffect(() => {
    document.title = 'CHINACYCLE 线上贸易对接会';
  });

  return (
    <div className={styles.page}>
      {isFail && <Modal message="您的申请已被预约，请选择其他时间段，敬请谅解！"></Modal>}
      <div className={styles.title}>商贸配对</div>
      <div className={styles.card}>
        <div className={styles.company}>
          <div
            className={styles.light}
            style={{
              marginBottom: 6,
            }}
          >
            Company Name:
          </div>
          <div
            className={styles.dark}
            style={{
              fontSize: 20,
            }}
          >
            {businessMatchDetail.companyName}
          </div>
        </div>
        <div
          className={styles.demand}
          style={{
            marginTop: 16,
          }}
        >
          <div
            className={styles.light}
            style={{
              marginBottom: 6,
            }}
          >
            实际采购需求:
          </div>
          <div
            className={styles.dark}
            style={{
              fontSize: 16,
            }}
          >
            {businessMatchDetail.demand}
          </div>
        </div>
        <div className={styles.info}>
          <div className={styles.flex}>
            <div className={styles.light}>Country Name:</div>
            <div className={styles.dark}>{businessMatchDetail.countryName}</div>
          </div>
          <div className={styles.flex}>
            <div className={styles.light}>Website:</div>
            <div
              className={styles.dark}
              style={{
                display: 'flex',
                alignItems: 'center',
                color: '#0053A3',
              }}
              onClick={() => {
                window.open(`https://${businessMatchDetail.website}`);
              }}
            >
              <img src={IconWebsite} />
              {businessMatchDetail.website}
            </div>
          </div>
          <div className={styles.flex}>
            <div className={styles.light}>Name:</div>
            <div className={styles.dark}>{businessMatchDetail.name}</div>
          </div>
          <div className={styles.flex}>
            <div className={styles.light}>Participant / Position:</div>
            <div className={styles.dark}>{businessMatchDetail.participant}</div>
          </div>
        </div>
      </div>
      <div
        className={styles.title}
        style={{
          marginTop: 20,
        }}
      >
        申请信息
      </div>
      <div className={styles.card}>
        <div className={styles.formItem}>
          {errorFields.includes('companyName') && <ErrorMessage message={'企业名称不能为空'} />}
          <div className={styles.label}>企业名称:</div>
          <div
            className={`${styles.inputWrapper} ${
              errorFields.includes('companyName') && styles.formItemError
            }`}
          >
            <input
              placeholder="请输入"
              className={styles.input}
              value={companyName}
              onChange={setCompanyName}
            />
          </div>
        </div>
        <div className={styles.formItem}>
          {errorFields.includes('venueNumber') && <ErrorMessage message={'请选择展馆'} />}
          <div className={styles.label}>馆号:</div>
          <div
            className={`${styles.inputWrapper} ${styles.venueWrapper} ${
              errorFields.includes('venueNumber') && styles.formItemError
            }`}
          >
            <Picker
              extra="请选择"
              cols={1}
              data={venues.map((item) => ({
                value: item,
                label: item,
              }))}
              value={[venueNumber]}
              onChange={(val) => {
                setVenueNumber(val[0]);
              }}
            >
              <List.Item arrow="down">馆号</List.Item>
            </Picker>
          </div>
        </div>
        <div className={styles.formItem}>
          {errorFields.includes('boothNumber') && <ErrorMessage message={'请输入正确的展位号'} />}
          <div className={styles.label}>展位号:</div>
          <div
            className={`${styles.inputWrapper} ${
              errorFields.includes('boothNumber') && styles.formItemError
            }`}
          >
            <input
              placeholder="请输入"
              className={styles.input}
              value={boothNumber}
              onChange={setBoothNumber}
            />
          </div>
        </div>
        <div className={styles.formItem}>
          {errorFields.includes('contact') && <ErrorMessage message={'联系人不能为空'} />}
          <div className={styles.label}>联系人:</div>
          <div
            className={`${styles.inputWrapper} ${
              errorFields.includes('contact') && styles.formItemError
            }`}
          >
            <input
              placeholder="请输入"
              className={styles.input}
              value={contact}
              onChange={setContact}
            />
          </div>
        </div>
        <div className={styles.formItem}>
          {errorFields.includes('mobile') && <ErrorMessage message={'请输入正确的手机号码'} />}
          <div className={styles.label}>联系方式:</div>
          <div
            className={`${styles.inputWrapper} ${
              errorFields.includes('mobile') && styles.formItemError
            }`}
          >
            <input
              placeholder="请输入"
              className={styles.input}
              value={mobile}
              onChange={setMobile}
            />
          </div>
        </div>
      </div>
      <div
        className={styles.title}
        style={{
          marginTop: 20,
        }}
      >
        申请时间
      </div>
      <div className={styles.card}>
        <div className={styles.date}>{applyDate}</div>
        <div className={styles.timeList}>
          {businessMatchDetail.businessOpportunityMeets &&
            businessMatchDetail.businessOpportunityMeets.map((item, index) => (
              <div
                className={`${styles.timeBox} ${styles.flex} ${
                  checkedTimeIndex == index && styles.radioChecked
                } ${item.reserved && styles.disableCheck}`}
                onClick={() => {
                  console.log(item.reserved);
                  if (item.reserved) {
                    return;
                  }
                  toggleTimeItem(index);
                }}
              >
                <div className={`${styles.radio}`}></div>
                <div className={`${styles.box}`}>
                  <div className={`${styles.applyInfo}`}>
                    <span>{formatTime(item.startTime, 'HH:mm')}</span> -{' '}
                    <span>{formatTime(item.endTime, 'HH:mm')}</span>
                  </div>
                  <div className={styles.applyLabel}>{item.reserved && '不'}可申请</div>
                </div>
              </div>
            ))}
        </div>
      </div>
      <div className={styles.submitBtn} onClick={submit}>
        提交
      </div>
    </div>
  );
}

export default Index;
